﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Publishing;
using System.Collections.Specialized;
using Inline.SharePoint.ExtendedVariations.Helpers;

namespace Inline.SharePoint.ExtendedVariations.Events
{

    /// <summary>
    /// List Events
    /// </summary>
    public class ListAddedEventHandler : SPListEventReceiver
    {

        private EventRegistrationHandler _eventRegistrationHandler = new EventRegistrationHandler();

        /// <summary>
        /// A list was added.
        /// </summary>
        public override void ListAdded(SPListEventProperties properties)
        {

            if (PublishingWeb.IsPublishingWeb(properties.Web))
            {

                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(properties.Web);
                StringCollection variationUrls = publishingWeb.VariationPublishingWebUrls;

                SPList list = properties.List;

                foreach (SPEventReceiverType rType in _eventRegistrationHandler.EventTypeClassRelation.Keys)
                {

                    _eventRegistrationHandler.DeleteRegisteredEventReceiver(list, rType, _eventRegistrationHandler.EventTypeClassRelation[rType].ToString());

                    if (!_eventRegistrationHandler.ListAlreadyHasEventReceiverRegistered(list, rType, _eventRegistrationHandler.EventTypeClassRelation[rType].ToString()))
                        list.EventReceivers.Add(rType, _eventRegistrationHandler.Assembly, _eventRegistrationHandler.EventTypeClassRelation[rType].ToString());

                }

                list.Update();

                try
                {

                    ListHandler listHandler = new ListHandler();
                    listHandler.RebuildListInAllOtherVariations(variationUrls, properties);

                }
                catch (Exception ex)
                {

                    Logger logger = new Logger();
                    logger.WriteEntry(properties.Web.Url,
                        "Inline.SharePoint.ExtendedVariations.Events::EventRegistrationHandler::ListAdded",
                        ex.Message + ex.StackTrace,
                        Logger.LogLevel.Error);

                }

            }

        }
          
    }

}
